package com.android.wellcherish.kotlindemo2

import java.lang.reflect.ParameterizedType

/**
 * @author 张文琛
 * @date 2020/8/16 22:41
 */
class TypeTest {
    // out：生产者，相当于 Java 中的 extends。可以作为函数的返回值
    // in： 消费者, 相当于 Java 中的 super。可以作为函数的参数

}

interface IView<out P: IPresenter<IView<P>>> {
    val presenter: P
}

interface IPresenter<out V: IView<IPresenter<V>>> {
    val view: V
}

abstract class BaseView<out P: BasePresenter<BaseView<P>>>: IView<P>{
    override val presenter: P

    //初始化presenter
    init {
        presenter = findPresenterClass().newInstance()
        presenter.view = this
    }

    private fun findPresenterClass(): Class<P>{
        var thisClass: Class<*> = this.javaClass
        while (true){
            (thisClass.genericSuperclass as? ParameterizedType)?.actualTypeArguments?.firstOrNull()
                ?.let {
                    return it as Class<P>
                }
                ?: run{
                    thisClass = thisClass.superclass ?: throw IllegalArgumentException()
                }
        }
    }
}

abstract class BasePresenter<out V: IView<BasePresenter<V>>>: IPresenter<V>{
    override lateinit var view: @UnsafeVariance V
}

class MainView: BaseView<MainPresenter>()

class MainPresenter: BasePresenter<MainView>()

fun main(args: Array<String>) {
    MainView().presenter.let(::println)
}